package classes;

import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import java.util.ArrayList;


public class ConfigTextExtractor extends DefaultHandler {

  private ArrayList<String> hierarchy = new ArrayList<String>();
  private static long sTime = 0;
  private static long fTime = 0;
  private ArrayList<Agent> list;
  private String name;
  private String path;
  private String service;
  private Boolean start;
   
  public void startDocument() throws SAXException 
	{
      System.out.println("Parsing is now begining...");
      sTime = System.currentTimeMillis();
	}
	
	public void endDocument() throws SAXException 
	{
		fTime = System.currentTimeMillis();
		System.out.println("Parsing file ended in: "+(new Long(fTime-sTime))+" ms!");
	}
	
  public ConfigTextExtractor(ArrayList<Agent> list) 
  {
    this.list = list;
  }
  
  public void startElement(String namespaceURI, String localName, String rawName, Attributes atts) throws SAXException 
	{
	  if (!hierarchy.contains(localName))
		  hierarchy.add(localName);
	}
	
	public void endElement(String namespaceURI, String localName,String rawName) throws SAXException 
	{
		if (localName.equals("Agent"))
			list.add(new Agent(this.name, this.path, this.service, this.start));
		
		if (hierarchy.contains(localName))
			  hierarchy.remove(hierarchy.indexOf(localName));
	}
	
	public void characters(char[] ch, int start, int end) throws SAXException 
	{
      String s = new String(ch, start, end);
      
      s = s.trim();
      
      if (s.length() > 0)
      {
	      if (hierarchy.contains("Name"))
	    	  this.name = s;
	      if (hierarchy.contains("Path"))
	    	  this.path = s;
	      if (hierarchy.contains("Service"))
	    	  this.service = s;
	      if (hierarchy.contains("Start"))
	    	  if (s.equals("true"))
	    		  this.start = true;
	    	  else this.start = false;
      }
	}
}
